import stocktransferApi from '../../../common/api/cbs/stocktransfer.api.js';
import doT from '../../../../vendor/template/doT.js';
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";
import { Select2Info, Select2Page } from "../../../common/serve-request.js";

let getEntryInfo = [], _pickerTime, _vm, attachesStr
const addsaleTemplate = doT.template($('#addsaleorders-template').text());
const curOrg = JSON.parse(Utils.GetSessionStorage('SNLoginUserInfo'));
(function (window, document, $) {
    const toolbarTemplate = `<div class="toolbar" id="me-date-screening"><div class="toolbar-inner">
<span style='margin:0 auto;margin-top:10px'>请选择业务日期</span><a href="javascript:;" class="picker-button close-picker" style="color:#427ce7;font-size:20px;margin-right:18px;display:inline-block;line-height:100%">{{closeText}}</a></div></div>`;
    $(function () {
        _vm = new Vue({
            el: "#addsaleorders-form",
            data() {
                return {
                    bizDate: moment(new Date()).format('YYYY-MM-DD'),
                    remark: '',
                    images: '',
                    stType: 2,
                    uploadCount: 0,
                    attaches: [],
                    inWarehouseId: '',
                    inWarehouseName: '',
                    inBreedBatchId: '',
                    inBreedBatchName: '',
                    outWarehouseId: '',
                    outWarehouseName: '',
                    outBreedBatchId: '',
                    outBreedBatchName: '',
                    outOrgUnitId: '',
                    outOrgUnitName: '',
                    inOrgUnitId: '',
                    inOrgUnitName: '',
                }
            },
            mounted() {
                let url = location.href
                let params = {} // url参数
                for (let key of (new URL(url)).searchParams.entries()) {
                    key[1] ? params[key[0]] = key[1] : ''
                }
                let ids = Utils.GetSessionStorage("ids")
                if (params.id || ids) {
                    document.title = '物料领用 - 编辑'
                }
            },

        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        // _datetimePickerInit();
        clickFun()
        _initCommand()
        uploadInit();
    });

    // 初始化数据
    const _initCommand = async () => {
        // 选择日期
        $('#search-date').on('click', function () {
            pick();
        });
        // 初始化所属组织
        let orglist = await stocktransferApi.getOrgList()
        $('#outOrgUnitId').select2({
            placeholder: '请选择调出组织...',//默认文字提示
            placeholderOption: "first",
            language: "zh-CN",//汉化
            allowClear: true,//允许清空
            data: orglist.map(item => {
                return {
                    id: item.oId,
                    text: item.oName,
                    ...item
                }
            }),
        });
        $('#outOrgUnitId').setSelectValue(curOrg?.coui, curOrg?.coun);
        _vm.outOrgUnitId = curOrg?.coui
        _vm.outOrgUnitName = curOrg?.coun

        // 初始化仓库
        let wareHouseArr = await stocktransferApi.getYfWareHouseList(curOrg?.coui)
        let wareHouseDefault = wareHouseArr.filter(item => { return item.isDefault == true })
        _vm.outWarehouseId = wareHouseDefault[0]?.id
        _vm.outWarehouseName = wareHouseDefault[0]?.name
        let inOrgUnitList = wareHouseArr.filter(item => { return item.isDefault != true })
        $(`#inWarehouseId`).empty().select2({
            placeholder: `请选择领用仓库...`,//默认文字提示
            language: "zh-CN",//汉化
            allowClear: true,//允许清空
            data: inOrgUnitList.map(item => {
                return {
                    text: item.name,
                    ...item
                }
            }),
        });
        $(`#inWarehouseId`).setSelectValue();

        // 选择仓库
        $(`#inWarehouseId`).on('select2:select', async function () {
            let selectinWarehouseId = $('#inWarehouseId').select2('data')[0]
            _vm.inWarehouseId = selectinWarehouseId.id
            _vm.inWarehouseName = selectinWarehouseId.name
        })

        // 初始化批次
        Select2Page($('#inBreedBatchId'), `${Utils.CurDomain.BaseCfgUrl}/breedbatchs/rlist`, (params) => {
            return JSON.stringify({
                farmOrgName: '',
                tags: '',
                name: params.term,
                sort: '',
                isEnd: false,
                farmOrgId: curOrg?.coui,
                pageSize: 20,
                pageIndex: (params.page || 1) - 1
            })
        }, "POST", {
            allowClear: true,//允许清空
            placeholder: '请选择领用批次…',
            templateResult: function (res) {
                return `${res.name}`;
            }
        });

        // 选择批次
        $(`#inBreedBatchId`).on('select2:select', async function () {
            let selectinBreedBatch = $('#inBreedBatchId').select2('data')[0]
            _vm.inBreedBatchId = selectinBreedBatch.id
            _vm.inBreedBatchName = selectinBreedBatch.name

            $('#salesEntry').empty().append(addsaleTemplate([]));
            JSON.stringify(Utils.SetSessionStorage("getEntryInfo", []))

        })

        // 编辑
        let ids = getUrlKey("id")
        if (Utils.IsNotNull(ids)) {
            $("#informationSubmit").text("保存");
            await stocktransferApi.getStockTransferBill(ids).then(async res => {
                Utils.SetRouterState('deliverDatas', res)
                JSON.stringify(Utils.SetSessionStorage("ids", ids))
                res.entries.forEach(async item => {
                    item.materialId = item.material?.id
                    item.materialName = item.material?.name
                    item.materialNumCode = item.material?.numCode
                    item.materialModel = item.material?.model
                    item.materialUnit = item.material?.baseMeasureUnit
                    // 查询价格
                    let _res = item.material?.numCode
                    if (Utils.IsNotNull(_res)) {
                        let info = {
                            "warehouseId": item.outWarehouse.id,
                            "bizDate": moment(res.createTime).format('YYYY-MM-DD'),
                            "materialId": item.material?.id,
                            "materialName": item.material?.name
                        }
                        if (_res.substring(0, 2) == "03") { //饲料03                           
                            let qty = await _curMaterialInfo(_res.substring(0, 2), info);
                            let price = await _breedbatchfeedprices(item.inBreedBatchId, item.material?.numCode);
                            item.curQty = qty.curQty
                            item.inPrice = price.inPrice
                            item.outPrice = price.outPrice
                            JSON.stringify(Utils.SetSessionStorage("getEntryInfo", res.entries))
                            $('#salesEntry').empty().append(addsaleTemplate(res.entries));
                        } else {
                            let curInfo = await _curMaterialInfo('', info);
                            item.curQty = curInfo.curQty
                            item.inPrice = curInfo.inPrice
                            item.outPrice = curInfo.outPrice
                            JSON.stringify(Utils.SetSessionStorage("getEntryInfo", res.entries))
                            $('#salesEntry').empty().append(addsaleTemplate(res.entries));
                        }
                    }
                })
            })
        }
        else {
            // 获取分录信息
            getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
            // 渲染 分录
            if (Utils.IsNotNull(getEntryInfo)) {
                $('#salesEntry').empty().append(addsaleTemplate(getEntryInfo));
            }
        }

        // 获取主表数据
        let getMainInfo = JSON.parse(Utils.GetSessionStorage("deliverDatas"))
        if (Utils.IsNotNull(getMainInfo)) {
            _vm.bizDate = getMainInfo.bizDate || moment(getMainInfo.bizFormObj?.bizDate).format('YYYY-MM-DD')
            _vm.remark = getMainInfo.remark
            _vm.inWarehouseId = getMainInfo.inWarehouseId || getMainInfo.entries[0]?.inWarehouse.id
            _vm.inWarehouseName = getMainInfo.inWarehouseName || getMainInfo.entries[0]?.inWarehouse.name
            _vm.inBreedBatchId = getMainInfo.inBreedBatchId || getMainInfo.entries[0]?.inBreedBatchId
            _vm.inBreedBatchName = getMainInfo.inBreedBatchName || getMainInfo.entries[0]?.inBreedBatchName
            $('#inBreedBatchId').setSelectValue(_vm.inBreedBatchId, _vm.inBreedBatchName);
            $('#inWarehouseId').setSelectValue(_vm.inWarehouseId, _vm.inWarehouseName);
            let editImage = []
            getMainInfo.attaches = getMainInfo.attaches || getMainInfo.images
            if (Utils.IsNotNull(getMainInfo.attaches) && !Utils.IsNotNull(ids)) {
                _images(getMainInfo.attaches)
                _vm.uploadCount = getMainInfo.uploadCount
            } else if (Utils.IsNotNull(getMainInfo.attaches)) {
                getMainInfo.attaches.split(',').forEach(item => {
                    editImage.push({
                        "imageId": item
                    })
                })
                _images(editImage)
                _vm.uploadCount = getMainInfo.attaches.split(',').length

            }
        }
    }

    const pick = () => {
        weui.datePicker({
            defaultValue: (moment(new Date()).format('YYYY-MM-DD')).split('-'),
            end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                _vm.bizDate = moment(new Date(value)).format('YYYY-MM-DD')
                $('#salesEntry').empty().append(addsaleTemplate([]));
                JSON.stringify(Utils.SetSessionStorage("getEntryInfo", []))
            }
        });// 默认配置
    }
    //查询批次饲料价格详情By批次Id
    const _breedbatchfeedprices = async (bid, numCode) => {
        let feedprices = await stocktransferApi.getFeedPrices(bid);
        let _feedPriceInfo = feedprices?.entries || 0;
        if (Utils.IsNotNull(_feedPriceInfo)) {
            let result = _feedPriceInfo.find(s => s.materialNumCode == numCode);
            return {
                inPrice: result?.price,
                outPrice: result?.price,
            }
        }
    }
    //查询即时库存物料价格
    const _curMaterialInfo = async (_res, info) => {
        if (Utils.IsNotNull(info.materialId)) {
            let materialPrice = await stocktransferApi.postCurinventoryPrice(info.materialId, info);
            let obj
            // 不是饲料
            if (!Utils.IsNotNull(_res)) {
                obj = {
                    inPrice: materialPrice?.price,
                    outPrice: materialPrice?.costPrice,
                }
            }
            return {
                curQty: materialPrice.curQty,
                ...obj
            }
        }
    }
    // 附件上传
    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                if (!isMobile() && files.length > 0) {
                    $.toptip('请使用手机拍照上传！', 'warning');
                    return false;
                }
                if (["image/jpg", "image/jpeg", "image/png"].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                $.showLoading('上传中..');
                _vm.uploadCount = ++_vm.uploadCount;
                if (_vm.uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: async function () {
                const file = this;
                let suffix = this.name.split('.').pop().toLowerCase(); //截取附件后缀
                let name = this.name.slice(0, 11 - (suffix.length) - 1); //计算截取文件的11位字符
                let newName = name + '.' + suffix
                let file1 = publicFileDraw(newName, _vm);
                // 在这里添加日期和地点水印
                const currentDate = moment(new Date()).format('YYYY-MM-DD')
                const currentTime = moment(new Date()).format('HH:mm:ss')
                const locationWatermark = $('#addressInfo').text()
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                const image = new Image();
                image.src = window.URL.createObjectURL(file);

                if (!Utils.IsNotNull(locationWatermark)) {
                    $.toptip('定位失败!', 'warning');
                    $.hideLoading();
                    $('#uploaderFiles').last().empty()
                    return
                }
                image.onload = function () {
                    canvas.width = image.width;
                    canvas.height = image.height;
                    // 在canvas上绘制原始图片
                    context.drawImage(image, 0, 0);

                    // 添加水印，支持换行
                    const watermarkText = currentDate + ' ' + currentTime + '\n' + locationWatermark;
                    context.font = '700 ' + 80 + 'px Arial';
                    context.fillStyle = 'white';

                    // 在指定位置绘制文本
                    const x = 10;
                    const y = image.height - 160;
                    drawWrappedText(context, watermarkText, x, y, 200, 130);  // 调用自定义函数

                    // 将canvas转为Blob
                    canvas.toBlob(function (blob) {
                        const formData = new FormData();
                        formData.append('apiobjfile', blob, file1);
                        _uploadFileDraw(formData, file, _vm);
                    }, file.type || 'image/png');  // 使用原始图片的类型或默认为PNG
                }
            }
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.attaches = _vm.attaches.filter(item => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 3) {
                                $(".weui-uploader__input-box").hide();
                            } else {
                                $(".weui-uploader__input-box").show();
                            }
                        },
                        onCancel: function () {
                        }
                    });
                }
            });
        });
    }
    // 自定义函数，用于在Canvas上绘制换行的文本
    function drawWrappedText(context, text, x, y, maxWidth, lineHeight) {
        var words = text.split('\n');
        var line = '';
        var yOffset = 0;

        for (var i = 0; i < words.length; i++) {
            var word = words[i];
            var testLine = line + word + ' ';
            var metrics = context.measureText(testLine);
            var testWidth = metrics.width;

            if (testWidth > maxWidth && i > 0) {
                context.fillText(line, x, y + yOffset);
                line = word + ' ';
                yOffset += lineHeight;
            } else {
                line = testLine;
            }
        }

        context.fillText(line, x, y + yOffset);
    }
    function isMobile() {
        return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    }
    // 附件上传
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile).then(async res => {
            if (res.isSucceed) {
                let imageurl = await requestFilePath(res.data)
                let _list = _vm.attaches;
                _list.push({
                    id: $("#uploaderFiles li").length,
                    imageId: res.data,
                    url: imageurl.data,
                });
                _vm.attaches = _list;
                $("#uploaderFiles li").each(function (i) {
                    $(this).attr('data-id', _vm.attaches[i].id);
                    $(this).attr('data-image-id', _vm.attaches[i].imageId);
                    $(this).attr('data-url', _vm.attaches[i].url);
                    $(this).css({ 'background-image': `url(${_vm.attaches[i].url})` });
                });
                $('.weui-uploader__file-content').hide();
                $('.weui-uploader__file').removeClass('weui-uploader__file_status');
            }
        }).catch(res => {
            $("#uploaderFiles li").eq($("#uploaderFiles li").length - 1).remove();
            _vm.uploadCount = --_vm.uploadCount;
            $.toptip(res.msg, 'error');
        }).finally(_ => {
            $.hideLoading();
            $.closeModal();
        });
    }
    // 编辑回显
    const _images = async (file) => {
        let _imag = file;
        if (_imag) {
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i].imageId).then(_res => {
                    _vm.attaches.push({
                        id: _sun,
                        url: _res.data,
                        imageId: _imag[i].imageId,
                    });
                    if (_res.isSucceed) {
                        let _li;
                        _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i].imageId}" style="background-image: url(${_res.data}) "></li>`;
                        $('#uploaderFiles').append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $(".weui-uploader__input-box").hide();
            }
            _vm.uploadCount = _sun;
        }
    }
    // //业务日期控件初始化
    // const _datetimePickerInit = () => {
    //     initCurrentDay()
    //     $('.sn-drop-down').on('click', function (e) {
    //         e.stopPropagation();
    //     });
    //     // 开始日期
    //     $('#search-date').on('click', function (e) {
    //         e.stopPropagation();
    //         $("#search-date").picker("open");
    //         _pickerDate();
    //     });
    //     $("#search-date").datetimePicker(
    //         {
    //             toolbarTemplate: toolbarTemplate,
    //             toolbarCloseText: "确定",
    //             toolbarCancelText: "取消",
    //             yearSplit: '年',
    //             monthSplit: '月',
    //             dateSplit: '日',
    //             times: function () {
    //                 return [];
    //             },
    //             //确定选择时的操作
    //             onClose: function (picker) {
    //                 let value = picker.value[0] + '-' + picker.value[1] + '-' + picker.value[2];
    //                 _pickerTime = '';
    //                 _pickerTime = value;
    //             }
    //         }
    //     );
    // }

    // //业务日期确认事件
    // const _pickerDate = () => {
    //     $(document).on("click", ".close-picker", async function () {
    //         $('#businessTime').val(_pickerTime);
    //         _vm.bizDate = _pickerTime
    //         $('#salesEntry').empty().append(addsaleTemplate([]));
    //         JSON.stringify(Utils.SetSessionStorage("getEntryInfo", []))
    //     });
    // }
    // // 业务日期获取当天
    // const initCurrentDay = () => {
    //     let todayDate = moment().format('YYYY-MM-DD')
    //     $('#businessTime').val(todayDate)
    //     _vm.bizDate = todayDate
    // }
    // 保存分录以上的内容
    const storeSession = () => {
        let _mainInfo = { bizDate: _vm.bizDate, remark: _vm.remark, attaches: _vm.attaches, uploadCount: _vm.uploadCount, inWarehouseId: _vm.inWarehouseId, inWarehouseName: _vm.inWarehouseName, inBreedBatchId: _vm.inBreedBatchId, inBreedBatchName: _vm.inBreedBatchName };
        let deliverDatas = { ..._mainInfo };
        // 保存数据内容
        Utils.SetRouterState('deliverDatas', deliverDatas)
    }

    // 操作函数
    const clickFun = () => {
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            // 删除分录 删除页面数据 删除ID
            window.sessionStorage.removeItem("getEntryInfo");
            window.sessionStorage.removeItem("deliverDatas");
            window.sessionStorage.removeItem("ids");
            location.href = `../stocktransfer/stocktransferlist.html?v=${Utils.GetTime()}`;
        });

        //取消，关闭弹框
        $(document).on('click', '#returnAddSaleOrders', function () {
            $('#pop').css('display', 'none');
            $('.show-box').css('display', 'none');
            $('.show-box').css({
                'bottom': '-6rem',
                'transition': 'all .ls ease-in'
            });
        });

        // 点击分录
        $('#add-saleEntry').on("click", function (e) {
            if (!Utils.IsNotNull(_vm.inWarehouseId)) {
                return $.toptip(`请选择领用仓库!`, 'warning');
            }

            if (!Utils.IsNotNull(_vm.inBreedBatchId)) {
                return $.toptip(`请选择领用批次!`, 'warning');
            }
            // 存储数据
            storeSession()
            // 获取分录 否则 默认是0
            let index = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))?.length || 0
            location.href = `../stocktransfer/stocktransentry.html?v=${Utils.GetTime()}&wid=${_vm.outWarehouseId}&bid=${_vm.inBreedBatchId}&biz=${_vm.bizDate}&index=${index}&isEdit=${false}`;
        })

        // 提交数据
        $('#informationSubmit').on("click", function (e) {
            let entries = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
            if (!Utils.IsNotNull(_vm.inWarehouseId)) {
                return $.toptip(`请选择领用仓库!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.inBreedBatchId)) {
                return $.toptip(`请选择领用批次!`, 'warning');
            }
            if (!Utils.IsNotNull(entries)) {
                return $.toptip(`请添加物料领用分录信息!`, 'warning');
            }
            savetips();
        })

        // 删除分录
        $(document).on('click', '#salesEntry div[data-flag=table-click-delete]', function () {
            let seq = $(this).data('index')
            $.modal({
                autoClose: false,
                title: '删除提示',
                text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认删除该分录?</div>
					</div>`,
                buttons: [
                    {
                        text: "取消", className: "default", onClick: function () {
                            $.closeModal();
                        }
                    },
                    {
                        text: "确定", onClick: function () {
                            let entries = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
                            // 过滤
                            let datas = entries.filter(item => item.seq != seq)

                            // 重置seq
                            let info = datas.map((item, index) => {
                                item.seq = index
                                return item
                            }) || []

                            // 赋值 
                            JSON.stringify(Utils.SetSessionStorage("getEntryInfo", info))
                            $('#salesEntry').empty().append(addsaleTemplate(info));
                            let totalCount = 0, allresion = []
                            info.map(item => {
                                totalCount += Number(item.count)
                                allresion.push(item.reasionName)
                            })
                            _vm.reasonNames = allresion.join(',')
                            _vm.totalCount = totalCount
                            _vm.totalWeight = Number(_vm.avgWeight) * Number(totalCount)
                            $.closeModal();
                        }
                    }
                ]
            });
        });

        // 编辑
        $(document).on('click', '#salesEntry div[data-flag=table-click-edit]', function () {
            // 存储数据
            storeSession()
            // 获取分录 否则 默认是0
            let index = $(this).data('index')
            location.href = `../stocktransfer/stocktransentry.html?v=${Utils.GetTime()}&wid=${_vm.outWarehouseId}&bid=${_vm.inBreedBatchId}&biz=${_vm.bizDate}&index=${index}&isEdit=${true}`;
        });
    }
    // 保存
    const savetips = () => {
        let tiptext = '是否确认保存该单据？'
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
                        <div class="addentry" >${tiptext}</div>
                    </div> 
                    </div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        $.closeModal();
                        let ids = Utils.GetSessionStorage("ids")
                        let entries = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))

                        let imageArr = []
                        _vm.attaches.forEach(item => {
                            imageArr.push(item.imageId)
                        })
                        let attachesStr = imageArr.join(',')
                        entries.forEach(item => {
                            item.inWarehouseId = _vm.inWarehouseId
                            item.inWarehouseName = _vm.inWarehouseName
                            item.inBreedBatchId = _vm.inBreedBatchId
                            item.inBreedBatchName = _vm.inBreedBatchName
                            item.outWarehouseId = _vm.outWarehouseId
                            item.outWarehouseName = _vm.outWarehouseName
                            item.outBreedBatchId = ''
                            item.outBreedBatchName = ''
                        })
                        let datas = {
                            bizDate: _vm.bizDate,
                            remark: _vm.remark,
                            images: attachesStr,
                            stType: 2,
                            outOrgUnitId: _vm.outOrgUnitId,
                            outOrgUnitName: _vm.outOrgUnitName,
                            inOrgUnitId: _vm.outOrgUnitId,
                            inOrgUnitName: _vm.outOrgUnitName,
                            entries: [...entries]
                        };
                        if (Utils.IsNotNull(ids)) {
                            return stocktransferApi.updateStockTransferBill(ids, JSON.stringify(datas)).then(res => {
                                $.toptip('请求成功。', 'success');
                                setTimeout(function () {
                                    window.sessionStorage.removeItem("getEntryInfo");
                                    window.sessionStorage.removeItem("deliverDatas");
                                    window.sessionStorage.removeItem("ids");
                                    location.href = `../stocktransfer/stocktransferlist.html?v=${Utils.GetTime()} `;
                                }, 1000);
                            })
                        }
                        else {
                            stocktransferApi.addStockTransferBill(JSON.stringify(datas)).then(res => {
                                $.toptip('请求成功。', 'success');
                                setTimeout(function () {
                                    window.sessionStorage.removeItem("getEntryInfo");
                                    window.sessionStorage.removeItem("deliverDatas");
                                    location.href = `../stocktransfer/stocktransferlist.html?v=${Utils.GetTime()} `;
                                }, 1000);
                            }, err => {
                                $.toptip(err.responseJSON?.msg, 'error');
                            });
                        }
                    }
                }
            ]
        });
    }

    // 获取地址栏的 参数 
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }
})(window, document, jQuery)